﻿using System.ServiceProcess;
using System.Timers;
using System;
using log4net;
using StructureMap;

namespace EnetaMvc.FeedAggregator
{
    public partial class AggregatorService : ServiceBase
    {
        private ILog _log;
        private object _lock = new object();
        private bool _working = false;
        private Timer _timer;

        public AggregatorService()
        {
            InitializeComponent();

            ObjectFactory.Initialize(container =>
            {
                //container.PullConfigurationFromAppConfig = true;
                container.For<ILog>().Use(LogManager.GetLogger(GetType()));
            });

            _log = ObjectFactory.GetInstance<ILog>();
        }

        protected override void OnStart(string[] args)
        {
            _timer = new Timer();
            _timer.Interval = 1000 * 60 * 5;
            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (_working)
                return;

            lock(_lock)
            {
                _working = true;
            }

            try
            {
                var client = new FeedClient();
                client.Execute();
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }

            lock (_lock)
            {
                _working = false;
            }
        }

        protected override void OnStop()
        {
            if (_timer != null)
            {
                _timer.Stop();
                _timer.Dispose();
                _timer = null;
            }
        }
    }
}
